package com.googlecode.pacswitch.actions;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import java.net.Proxy.Type;
import java.net.URL;
import java.nio.channels.AsynchronousSocketChannel;

import javax.xml.bind.annotation.XmlAccessOrder;
import javax.xml.bind.annotation.XmlAccessorOrder;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlType;

import com.googlecode.pacswitch.ObjectFactory;
import com.googlecode.pacswitch.PInteger;
import com.googlecode.pacswitch.PString;
import com.googlecode.pacswitch.PacSwitch;
import com.googlecode.pacswitch.PropertyValue;

/**
 * @author Andrey Pavlenko
 */
@XmlType(name = "Proxy", namespace = ObjectFactory.ANS)
@XmlAccessorOrder(XmlAccessOrder.ALPHABETICAL)
public class Proxy extends Pac implements PropertyValue {
    private PString _host;
    private PInteger _port;

    @XmlAttribute(required = true)
    public PString getHost() {
        return _host;
    }

    public void setHost(final PString host) {
        _host = host;
    }

    @XmlAttribute(required = true)
    public PInteger getPort() {
        return _port;
    }

    public void setPort(final PInteger port) {
        _port = port;
    }

    @Override
    public String resolve(final PacSwitch ps,
            final AsynchronousSocketChannel clientSocket) {
        return _host.resolve(ps, clientSocket) + ':'
                + _port.resolveInt(ps, clientSocket);
    }

    public long test(final PacSwitch ps, final URL url) throws IOException {
        final java.net.Proxy proxy = new java.net.Proxy(Type.HTTP,
                new InetSocketAddress(_host.resolve(ps, null),
                        _port.resolveInt(ps, null)));
        final HttpURLConnection c = (HttpURLConnection) url
                .openConnection(proxy);
        final InputStream in = c.getInputStream();
        final byte[] buf = new byte[2048];
        final long time = System.currentTimeMillis();

        while (in.read(buf) != -1) {
        }

        return System.currentTimeMillis() - time;
    }

    @Override
    protected String resolveBody(final PacSwitch ps,
            final AsynchronousSocketChannel clientSocket) {
        return body("PROXY " + resolve(ps, clientSocket));
    }

    static String body(final String proxies) {
        return "function FindProxyForURL(url, host) {\r\n    return \""
                + proxies + "\";\r\n}";
    }
}
